<template>
  <div v-if="!paramsError" class="app-container detail-container">
    <div class="detail-title">
      {{ textMap[type] }}
    </div>
    <el-form
      ref="form"
      :disabled="formDisabled"
      :rules="rules"
      :model="form"
      :label-width="labelWidth"
      class="detail-form">
      <el-row :gutter="100">
        <el-col :span="10">
          <el-form-item :label="lang.systemManage.role.index.tableCol.roleName" prop="roleName">
            <el-input v-model.trim="form.roleName" :placeholder="`请输入${lang.systemManage.role.index.tableCol.roleName}`" maxlength="50"/>
          </el-form-item>
          <el-form-item :label="lang.systemManage.role.index.tableCol.roleCode" prop="roleCode">
            <el-input v-model.trim="form.roleCode" :placeholder="`请输入${lang.systemManage.role.index.tableCol.roleCode}`" maxlength="50"/>
          </el-form-item>
          <el-form-item :label="lang.systemManage.role.index.tableCol.remark">
            <el-input v-model.trim="form.remark" :autosize="{minRows: 5, maxRows: 10}" :placeholder="`请输入${lang.systemManage.role.index.tableCol.remark}`" type="textarea" maxlength="180"/>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item :label="lang.systemManage.role.index.tableCol.function" prop="ids">
            <div class="detail-tree">
              <div class="buttons">
                <el-button type="default" size="mini" plain @click="functionCheckSet()">全选/取消</el-button>
                <!-- <el-button type="default" size="mini" plain @click="functionExpandAll = !functionExpandAll">展开/关闭</el-button> -->
              </div>
              <el-tree
                ref="elTreeRef"
                :is-loading="functionLoading"
                :data="functionTree"
                :props="functionProps"
                :default-expand-all="functionExpandAll"
                :default-checked-keys="form.functionIdList"
                node-key="id"
                empty-text="暂无数据"
                highlight-current
                show-checkbox
                @check-change="functionCheckChange" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div :style="{'padding-left': labelWidth}" class="detail-buttons">
      <el-button
        v-waves
        v-if="type === 'create' && $$roleBtn('systemManage.role.add')"
        :loading="saveLoading"
        type="primary"
        @click="save()">提交</el-button>
      <el-button
        v-waves
        v-if="type === 'detail' && $$roleBtn('systemManage.role.edit')"
        :loading="saveLoading"
        type="primary"
        @click="edit()">更新</el-button>
      <el-button v-waves type="default" @click="$$closeTag()">关闭</el-button>
    </div>
  </div>
</template>

<script>
import CloseTagMixin from '@/mixins/closeTag'
import { getRoleById, roleAdd, roleUpdate } from '@/api/systemManage/role'
import { getFunctionTree } from '@/api/systemManage/function'
import waves from '@/directive/waves' // Waves directive
import { mapGetters } from 'vuex'

export default {
  name: 'RoleManageItem',
  directives: { waves },
  components: {
  },
  mixins: [CloseTagMixin],
  data() {
    const langIndex = this.$store.getters.lang.systemManage.role.index
    const langDetail = this.$store.getters.lang.systemManage.role.detail
    return {
      textMap: {
        create: langDetail.titleTag.create2,
        detail: langDetail.titleTag.detail
      },
      labelWidth: '100px',
      id: this.$route.params.id,
      type: this.$route.params.type,
      saveLoading: false,
      paramsError: false,
      selectHeadImgInput: null,
      headImg: null,
      form: {},
      defaultPassword: this.$store.getters.defaultPassword,
      rules: {
        roleName: [
          { required: true, message: `请输入${langIndex.tableCol.roleName}`, trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: `请输入${langIndex.tableCol.roleCode}`, trigger: 'blur' }
        ]
      },
      functionLoading: false,
      functionTree: [],
      functionProps: {
        label: 'sysName'
      },
      functionIsCheckAll: false,
      functionExpandAll: false
    }
  },
  computed: {
    ...mapGetters([
      'lang'
    ]),
    formDisabled() {
      switch (this.type) {
        case 'create': return !this.$$roleBtn('systemManage.role.add')
        case 'detail': return !this.$$roleBtn('systemManage.role.edit')
      }
    }
  },
  created() {
    // 参数type验证
    switch (this.type) {
      case 'create':
        // 设置标签名称
        this.$store.dispatch('setTagName', {
          path: this.$route.path,
          title: this.lang.systemManage.role.detail.titleTag.create
        })
        break
      case 'detail': this.getInfo(); break
      default: {
        this.paramsError = true
        this.$message.info('页面参数不正确，请重新打开页面！')
        return
      }
    }
    // 初始化数据模板
    this.getFunction()
    this.formReset()
  },
  methods: {
    formReset() {
      this.form = {
        roleName: '',
        roleCode: '',
        remark: '',
        ids: []
      }
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.functionCheckSet(false)
      })
    },
    getInfo() {
      getRoleById(this.id).then(res => {
        const data = res.data
        this.form = data
        if (!Array.isArray(this.form.ids)) this.form.ids = []
        // 设置标签名称
        this.$store.dispatch('setTagName', {
          path: this.$route.path,
          title: `${data.roleName}-${this.lang.systemManage.role.detail.titleTag.detail}`
        })
      }).catch(e => {
        this.$message.error(this.$store.getters.errorMsg)
      })
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          roleAdd(this.form).then(res => {
            this.saveLoading = false
            if (res.code === 200) {
              this.$message.success('创建成功！')
              this.formReset()
            } else {
              this.$message.error(res.message)
            }
          }).catch(e => {
            this.this.saveLoading = false
            this.$message.error(this.$store.getters.errorMsg)
          })
        } else return false
      })
    },
    edit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          roleUpdate(this.form).then(res => {
            this.saveLoading = false
            if (res.code === 200) {
              this.$message.success('更新成功！')
            } else {
              this.$message.error(res.message)
            }
          }).catch(e => {
            this.saveLoading = false
            this.$message.error(this.$store.getters.errorMsg)
          })
        } else return false
      })
    },
    getFunction() {
      this.functionLoading = true
      getFunctionTree({ type: 1 }).then(res => {
        this.functionLoading = false
        if (res.code === 200) {
          this.functionTree = res.data
        } else this.$message.error(res.message)
      }).catch(e => {
        this.functionLoading = false
        this.$message.error(this.$store.getters.errorMsg)
      })
    },
    functionCheckSet(type) {
      this.functionIsCheckAll = type !== undefined ? type : !this.functionIsCheckAll
      if (this.functionIsCheckAll) {
        const keys = this.getFunctionAllKey(this.functionTree)
        this.$refs.elTreeRef.setCheckedKeys(keys)
      } else {
        this.$refs.elTreeRef.setCheckedKeys([])
      }
    },
    getFunctionAllKey(nodes) {
      const arr = []
      for (let i = 0; i < nodes.length; i++) {
        arr.push(nodes[i].id)
        if (Array.isArray(nodes[i].children) && nodes[i].children.length) {
          arr.push(...this.getFunctionAllKey(nodes[i].children))
        }
      }
      return arr
    },
    functionCheckChange() {
      const keys = this.$refs.elTreeRef.getCheckedKeys()
      this.form.ids = keys
      this.$forceUpdate()
      console.log(this.form)
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-tree{
  position: relative;
  min-height: 350px;
  // background-color: #fdfdfd;
  border: 1px solid #ddd;
  padding: 15px;
  padding-top: 46px;
  border-radius: 4px;
  .buttons{
    position: absolute;
    right: 20px;
    top: 4px;
  }
}
</style>

